package com.chenjt.netty.ten_zerocopy;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2024/9/2 10:33
 */
public class NewIOServer {

    public static void main(String[] args) throws Exception {

        InetSocketAddress address = new InetSocketAddress(8899);

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        ServerSocket serverSocket = serverSocketChannel.socket();
        /**
         * TCP连接关闭之后，不会立刻释放，会保持一段时间的连接，这时候的状态是：TIME_WAIT，
         * 该连接占用的端口是没办法被其他端口所使用的
         *
         * 如果想要处于 TIME_WAIT 状态下的端口能被其他新建立的TCP连接所使用，在bind之后调用一下
         * setReuseAddress(true)即可
         *
         * 一定要在bind之前去调用 setReuseAddress
         */
        serverSocket.setReuseAddress(true);
        serverSocket.bind(address);


        ByteBuffer byteBuffer = ByteBuffer.allocate(4096);

        while(true){
            SocketChannel socketChannel = serverSocketChannel.accept();
            // 配置为阻塞状态
            socketChannel.configureBlocking(true);

            int readCount = 0;

            while(-1 != readCount){
                try {
                    readCount = socketChannel.read(byteBuffer);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // position重置为0
                byteBuffer.rewind();
            }

        }



    }


}
